package com.dzsw.e2p.config;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.office.InstalledOfficeManagerHolder;
import org.jodconverter.core.office.OfficeUtils;
import org.jodconverter.local.LocalConverter;
import org.jodconverter.local.office.LocalOfficeManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class JodConverterConfig {

    private JodCConf conf;

    private LocalOfficeManager officeManager;

    public JodConverterConfig(JodCConf conf) {
        this.conf = conf;
    }

    @PostConstruct
    public void init() {
        int[] ports = conf.getPortNumbers().stream().mapToInt(Integer::valueOf).toArray();
        this.officeManager = LocalOfficeManager.builder()
                .officeHome(conf.getOfficeHome())
                .hostName(conf.getHostName())
                .portNumbers(ports)
                .processTimeout(conf.getProcessTimeout())
                .maxTasksPerProcess(conf.getMaxTasksPerProcess())
                .workingDir(conf.getWorkingDir())
                .build();
        try {
            this.officeManager.start();
            System.out.println(this.officeManager.isRunning());
            InstalledOfficeManagerHolder.setInstance(officeManager);
            log.info("Office manager started");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    public LocalOfficeManager getOfficeManager() {
        return this.officeManager;
    }

    @Bean
    public DocumentConverter documentConverter() {
        LocalConverter converter = LocalConverter.builder()
                .officeManager(this.officeManager)
                .build();
        return converter;
    }

    @PreDestroy
    public void destroy() {
        if (null != officeManager && officeManager.isRunning()) {
            log.info("stop office manager...");
            OfficeUtils.stopQuietly(officeManager);
            log.info("office manager stopped.");
        }
    }
}
